package org.example.service;

import lombok.extern.slf4j.Slf4j;
import org.example.config.RedisCache;
import org.example.entity.UserInfo;
import org.example.entity.UserLogin;
import org.example.util.CommonResult;
import org.example.util.JwtUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author: gx.wu
 * @create: 2023-05-09 15:25
 * @Description:
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService{

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;


    @Override
    public CommonResult<Object> login(UserInfo user) {
        log.info("user：{}", user);
        //进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //认证未通过，给出提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登陆失败！");

        }
        //通过了，生成jwt
        UserLogin loginUser = (UserLogin) authenticate.getPrincipal();
        String id = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(id);
        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);
        //将用户信息存入redis
        redisCache.setCacheObject("login"+id,loginUser);
        return CommonResult.success(map,"登陆成功！");
    }
}
